package client;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import common.ClientInterface;
import common.Game;
import common.ServerInterface;
import common.characters.CharacterInterface;

public class RMIClient extends UnicastRemoteObject implements ClientInterface {
	private static final long serialVersionUID = 1L;
	private ServerInterface server;
	private int player;
	private ClientController controller;

	public RMIClient(final ClientController cc, final String IP,
			final String playerName, final CharacterInterface character)
			throws RemoteException {
		try {
			// this.server = (ServerInterface) Naming.lookup("ProServer");
			this.server = (ServerInterface) Naming.lookup(IP);
			connectToServer(playerName, character, IP);
			this.controller = cc;
			this.controller.addClient(this);
			this.server.requestStart(this.player);
			System.out.println("Client is ready.\n__________");
		} catch (final Exception e) {
			System.out.println("RMIClient exception: " + e);
			e.printStackTrace();
		}
	}

	public int getThisPlayerNumber() {
		return this.player;
	}

	private void connectToServer(final String playerName,
			final CharacterInterface character, final String ipNumber) {
		try {
			this.player = this.server.connectClient(this, playerName,
					character, ipNumber);
		} catch (final RemoteException e) {
			System.out.println("Connect to server failed");
			e.printStackTrace();
		}
	}

	public void diceRolled() {
		try {
			this.server.diceRolled(this.player);
		} catch (final RemoteException e) {
			System.out.println("Dice rolled failed!(RMIClient)");
			e.printStackTrace();
		}
	}

	public void tileChosen(final int i) {
		try {
			this.server.tileChosen(i, this.player);
		} catch (final RemoteException e) {
			System.out.println("tileChosen failed! (RMIClient");
			e.printStackTrace();
		}
	}

	@Override
	public void update(final Game sg) throws RemoteException {
		this.controller.update(sg);

	}

	@Override
	public void observerUpdate(final Game sg) throws RemoteException {
		this.controller.observerUpdate(sg);

	}

	@Override
	public void shutdownClient(final String txt) {
		System.out.println("Reason for client shutdown: " + txt);
		System.exit(0);
	}

	public void tileEvent() {
		try {
			this.server.tileEvent(this.player);
		} catch (final RemoteException e) {
			System.out.println("tileEvent at RMIClient caused an exception");
			e.printStackTrace();
		}

	}

	public void tileEventContinue() {
		try {
			this.server.tileEventContinue(this.player);
		} catch (final RemoteException e) {
			System.out
					.println("tileEventContinue at RMIClient caused an exception");
			e.printStackTrace();
		}
	}
}
